package com.bigfans.framework.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bigfans.framework.dao.DynamicDataSourceHolder;

@Aspect
@Order(-1)
@Component
public class DynamicDataSourceAspect {

	private static final String TRANSACTION = "@annotation(transactional)";
	private static final ThreadLocal<Method> startMethod = new ThreadLocal<Method>();
	
	@Before(TRANSACTION)
	public void changeDataSource (JoinPoint call, Transactional transactional) {
		MethodSignature methodSignature = (MethodSignature)call.getSignature();
		Method method = methodSignature.getMethod();
		String methodName = method.getName();
		if(startMethod.get() == null){
			startMethod.set(method);
		}
		boolean readOnly = transactional.readOnly();
		if (readOnly) {
			DynamicDataSourceHolder.read();
		} else {
			DynamicDataSourceHolder.write();
		}
	}
	
	@After(TRANSACTION)
	public void restoreDataSource(JoinPoint call, Transactional transactional) {
		MethodSignature methodSignature = (MethodSignature)call.getSignature();
		Method method = methodSignature.getMethod();
		String methodName = method.getName();
		if(method == startMethod.get()){
			DynamicDataSourceHolder.clearDataSource();
			startMethod.remove();
		}
	}
	
}
